#include "head.h"

int net_gets(request_t *request, int net_fd, MYSQL *mysql){
    // printf("nets_gets start\n");
    LOG(INFO, request->user_name, "gets", "开始执行gets操作");
    MYSQL_RES *res;
    MYSQL_ROW row;

    response_t response;
    bzero(&response, sizeof(response));

    int user_id = get_user_id(request->user_name, mysql);
    if(user_id == -1){
        response.status = 1;
        sprintf(response.args, "User information error.\n");
        send(net_fd, &response, sizeof(response), MSG_NOSIGNAL);
        return -1;
    }

    char query[1024] = {0};
    char str[160] = {0};
    strcpy(str, request->path);
    if(strcmp(str, "/")){
        strcat(str, "/");
    }
    strcat(str, request->args);
    sprintf(query, "select file_hash,file_size from files \
            where filename = '%s' and user_id = %d and path = '%s' and delete_flag = 1", 
            request->args, user_id, str);
    //查找文件
    if(mysql_query(mysql, query)){
        printf("%s\n", mysql_error(mysql));
        sprintf(response.args, "Server error.\n");
        send(net_fd, &response, sizeof(response), MSG_NOSIGNAL);
        return -1;
    }

    //获取结果集
    res = mysql_store_result(mysql);
    //检查文件是否存在
    if(res == NULL){
        response.status = 1;
        sprintf(response.args, "File does not exists.\n");
        send(net_fd, &response, sizeof(response), MSG_NOSIGNAL);
        mysql_free_result(res);
        return -1;
    }
    //向客户端发送响应报文
    send(net_fd, &response, sizeof(response), MSG_NOSIGNAL);

    row = mysql_fetch_row(res);
    char file_hash[FILE_HASH_SIZE + 1] = {0}; 
    strcpy(file_hash, row[0]);
    off_t file_size = atoi(row[1]);

    mysql_free_result(res);

    send_file(file_hash, file_size, net_fd);
    return 0;
}
